<script setup lang="ts">
import { defineProps, ref, watch, reactive } from "vue"
import {
  FormInst,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NUpload,
  NSelect,
  NInputNumber,
  NImage,
  NSwitch,
} from "naive-ui"
import { getOssApi } from "@api/index"

const props = defineProps<{
  showModal: boolean
  modalSubmit: (data: any) => void
  modalClose: () => void
  handleUpdateGoods: (data: any) => void
  editConfig: any
  cateList: Array<any>
  statusOptions: Array<any>
}>()

const formRef = ref<FormInst | null>(null)
const ossConfig: any = ref({})
const fileList = ref<any>([])

const formValue: any = reactive({
  data: <any>{
    imagesList: []
  },
})
const rules = {
  imagesList: {
    required: true,
    message: "请上传图片",
  },
  orderName: {
    required: true,
    message: "请输入商品名称",
  },
  catelogId: {
    required: true,
    message: "请选择商品分类",
  },
  showStatus: {
    required: true,
    message: "请选择商品状态",
  },
  price: {
    required: true,
    message: "请输入商品价格",
  },
  priceDiscounts: {
    required: true,
    message: "请输入优惠价格",
  },
  priceCost: {
    required: true,
    message: "请输入成本价格",
  },
  stockCount: {
    required: true,
    message: "请输入商品库存",
  },
  orderDescribed: {
    required: true,
    message: "请输入商品描述",
  },
}

const clearFormValue = () => {
  formValue.data = {}
  fileList.value = []
}

//弹窗确认
const modalOnOk = () => {
  // console.log('弹窗确认');
  formRef.value?.validate((errors) => {
    if (!errors) {
      // console.log('表单验证通过');
      if (props.editConfig.isEdit) {
        props.handleUpdateGoods({ orderId: props.editConfig.echoData.orderId, ...formValue.data, imagesList: fileList.value })
        clearFormValue()
      } else {
        props.modalSubmit({ ...formValue.data, imagesList: fileList.value })
        clearFormValue()
      }
    }
  })
}
//弹窗关闭
const modalCancel = () => {
  props.modalClose()
  clearFormValue()
  fileList.value = []
}
//上传图片前回调
const beforeUpload = async (file: any) => {
  file.file.name = Date.now().toString() + '.' + file.file.type.slice(6)
  ossConfig.value = await getOssApi({})

}
//上传图片时携带的数据
const dataReturn = (file: any) => {
  return {
    key: ossConfig.value.data.dir + file.file.name,
    OSSAccessKeyId: ossConfig.value.data.accessid,
    ...ossConfig.value.data,
    success_action_status: "200"
  }
}
//上传完成回调
const uploadFinish = (file: any) => {
  if (file.file.status === "finished") {
    // formValue.data.imagesList = formValue.data.imagesList.map((item: any) => {
    //   return {
    //     ...item,
    //     imgUrl: `${ossConfig.value.data.host}/${ossConfig.value.data.dir}${file.file.name}`,
    //     url: `${ossConfig.value.data.host}/${ossConfig.value.data.dir}${file.file.name}`,
    //     defaultImg: 0,
    //     status: 'finished',
    //   }
    // })
    // fileList.value = formValue.data.imagesList
    fileList.value.push({
      imgUrl: `${ossConfig.value.data.host}/${ossConfig.value.data.dir}${file.file.name}`,
      defaultImg: 0,
      status: 'finished',
      url: `${ossConfig.value.data.host}/${ossConfig.value.data.dir}${file.file.name}`,
      id: `${ossConfig.value.data.host}/${ossConfig.value.data.dir}${file.file.name}`,
      name: `${file.file.name}`,
    })
  }
  //  
  //   // fileList.value = formValue.data.imagesList
  // }
}
//文件删除时的回调
const uploadRemove = (files: any) => {
  // fileList.value = formValue.data.imagesList.map((item: any) => {
  //   return {
  //     ...item,
  //     imgUrl: `${ossConfig.value.data.host}/${ossConfig.value.data.dir}${item.name}`,
  //     defaultImg: 0,
  //   }
  // })
  fileList.value = fileList.value.filter((item: any) => {
    return item.name !== files.file.name
  })

}


//编辑分类的监听回调
watch(() => props.editConfig, (newValue, oldValue) => {
  if (newValue.isEdit === true) {
    formValue.data = {
      ...newValue.echoData,
      imagesList: newValue.echoData?.imagesList?.map((item: any) => {
        return {
          status: 'finished',
          url: item.imgUrl ?? '',
          defaultImg: item.defaultImg,
          imgUrl: item.imgUrl ?? '',
          // id: item.imgUrl ?? '',
          name: item.imgUrl ? item.imgUrl?.split('/')?.slice(-1)?.toString() : '',
        }
      })
    }
    fileList.value = newValue.echoData?.imagesList?.map((item: any) => {
      return {
        status: 'finished',
        defaultImg: item.defaultImg,
        imgUrl: item.imgUrl,
        name: item.imgUrl.split('/').slice(-1).toString(),
      }
    })
  }
  // console.log(formValue.data);
}, {
  deep: true
});

const checkDefaultImg = (checked: boolean, value: any) => {
  // if (checked) {
  fileList.value.forEach((item: any, index: number) => {
    if (item.imgUrl === value.imgUrl) {
      fileList.value[index] = { ...item, defaultImg: 1 }
    } else {
      fileList.value[index] = { ...item, defaultImg: 0 }
    }
  });
  // } else {
  //   fileList.value.forEach((item: any, index: number) => {
  //     if (item.imgUrl === value.imgUrl) {
  //       fileList.value[index] = { ...item, defaultImg: 0 }
  //     }
  //   });
  // }
}

</script>

<template>
  <div class="modal">
    <n-modal :show="props.showModal" preset="dialog" :title="props.editConfig.isEdit ? '编辑商品' : '新增商品'" positive-text="确认"
      negative-text="取消" @positive-click="modalOnOk" @negative-click="modalCancel" :show-icon="false"
      :on-close="modalCancel" :on-mask-click="modalCancel">
      <n-form ref="formRef" label-placement="left" :model="formValue.data" :rules="rules">
        <n-form-item label="图片:" path="imagesList">
          <n-upload :max="5" accept=".png,.jpg" list-type="image-card" v-model:file-list="formValue.data.imagesList"
            :action="ossConfig?.data?.host" :on-before-upload="beforeUpload" :data="dataReturn" :on-change="uploadFinish"
            :on-remove="uploadRemove">
          </n-upload>
        </n-form-item>
        <n-form-item label="商品名称:" path="orderName">
          <n-input class="form_item" v-model:value="formValue.data.orderName" placeholder="请填写商品名称" />
        </n-form-item>
        <n-form-item label="商品类型:" path="catelogId">
          <n-select class="form_item" v-model:value="formValue.data.catelogId" placeholder="请选择商品类型"
            :options="cateList" />
        </n-form-item>
        <n-form-item label="状态:" path="showStatus">
          <n-select class="form_item" v-model:value="formValue.data.showStatus" placeholder="请选择商品状态"
            :options="props.statusOptions" />
        </n-form-item>
        <n-form-item label="成本:" path="priceCost">
          <n-input-number clearable min="0" class="form_item" v-model:value="formValue.data.priceCost"
            placeholder="请填写商品成本" />
        </n-form-item>
        <n-form-item label="原价:" path="price">
          <n-input-number clearable min="0" class="form_item" v-model:value="formValue.data.price"
            placeholder="请填写商品价格" />
        </n-form-item>
        <n-form-item label="优惠价:" path="priceDiscounts">
          <n-input-number clearable min="0" class="form_item" v-model:value="formValue.data.priceDiscounts"
            placeholder="请填写商品优惠价" />
        </n-form-item>
        <n-form-item label="库存:" path="stockCount">
          <n-input-number clearable min="0" class="form_item" v-model:value="formValue.data.stockCount"
            placeholder="请填写商品库存" />
        </n-form-item>
        <n-form-item label="商品描述:" path="orderDescribed">
          <n-input type="textarea" clearable class="form_item" v-model:value="formValue.data.orderDescribed"
            placeholder="请填写商品描述" />
        </n-form-item>
        <n-form-item label="选择默认图片:">
          <div class="defaultImg" v-for="item in fileList">
            <div class="row">
              <n-image width="50" :src="item.imgUrl" />
              <n-switch size="small" :value="item.defaultImg === 1 ? true : false"
                v-on:update-value="(checked) => checkDefaultImg(checked, item)" class="switch" />
            </div>
          </div>
        </n-form-item>

      </n-form>
    </n-modal>
  </div>
</template>

<style lang="scss" scoped>
.form_item {
  width: 180px;
}

.defaultImg {
  display: flex;
  // flex: 1;
  flex-wrap: wrap;

  .row {
    display: flex;
    flex-direction: column;
    margin-right: 18px;
    justify-content: center;
    align-items: center;

    .switch {
      margin-top: 10px;
    }
  }
}
</style>
